package com.metamedia.test;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;

public class Driver {

	/**
	 * @param args
	 * @throws IOException
	 */
	public static void main(String[] args) {
		// double[] numbers = new double[] { 1, 2, 3, 9, 4, 5, 3, 3, 5, 6, 1, 3,
		// 565, 4, 65, 845, 32123, 45113, 5, 654 };
		Scanner in = new Scanner(System.in);
		String s = "";
		do {
			System.out.print("Enter a fileName- ");

			try {

				s = in.nextLine();
				List<Operation> operations = getOperations(s);
				for (Operation operation : operations) {
					System.out.println(operation);
				}

			} catch (Exception e) {
				e.printStackTrace();
				System.out.println("\nPlease enter a FileName!");

			}

		} while (!s.equalsIgnoreCase("exit"));
		in.close();

	}

	public static List<Operation> getOperations(String fileName)
			throws IOException {

		List<Operation> operations = new ArrayList<>();
		BufferedReader br = new BufferedReader(new FileReader(fileName));
		String line;
		while ((line = br.readLine()) != null) {
			try {
				operations.add(getOperation(line));
			} catch (Exception e) {
				System.err.println("Incorrect line");
			}
		}
		br.close();
		return operations;
	}

	public static Operation getOperation(String line) {
		int colonIndex = line.indexOf(":");
		String operationType = line.substring(0, colonIndex).trim();
		String numberStrings = line.substring(colonIndex + 1).trim();
		List<String> numbersList = Arrays.asList(numberStrings.split(","));
		double[] numbers = new double[numbersList.size()];
		int i = 0;
		for (String numberString : numbersList) {
			numbers[i++] = Double.parseDouble(numberString.trim());
		}
		return Operation.getOperation(operationType, numbers);
	}
}
